<?php
/*
 * passport 控制器 
 *
 */
class Controller_Passport extends Controller_Admin_Template 
{
	private $_passport = NULL;

	public function __construct(Request $req, Response $res)
	{
		$action = $req->action();
		if (! in_array($action, array('passwd', 'logout', 'login_callback', 'window')) &&
			(user::is_login() || user::current_merchant_uid() > 0))
		{
			$req->redirect('http://'.Site::domain('merchant'));
		}

		parent::__construct($req, $res);
		$this->template  = 'smarty:blank';
		$this->_passport = new Passport();
	}

	public function action_window ($type)
	{
		//sleep(1);
		if ($type == 'login')
		{
			if ($this->request->is_ajax())
			{
				$content = view::factory('smarty:passport/widget/login_window')->render();
				echo json_encode(array('status' => 0, 'content' => $content));
				exit;
			}
			$this->template->set_filename('smarty:passport/widget/login_window');
		}
	}

	/*
	 * 默认入口
	 *
	 *	已登录，自动跳转到首页
	 *	未登录，展示登录页
	 */
	public function action_index()
	{
		if (user::is_login())
			$this->request->redirect('/');
		else
			$this->action_login();
	}


	/*
	 * 标准登录入口
	 */
	public function action_login ()
	{
		$this->template->set_filename('smarty:passport/login');

		//$sohu_passport_regsucc = Arr::get($this->request->query(), 'passport_reg', 0);
		//$title = '登录';
		//$include_jquery_validation = FALSE;
		//if (isset($_GET['register']) AND !empty($_GET['register']))
		//{
		//	$title = '注册，登录';
		//	$include_jquery_validation = TRUE;
		//}

		//$this->template->set("page_title", '请登录');
		//$this->template->set("sohu_passport_regsucc", $sohu_passport_regsucc); 
		//$this->template->set("login_prompt", Passport::login_prompt());
		$this->template->set("return_url", $this->url_login_ru()); 
		//$this->template->set("include_jquery_validation", $include_jquery_validation);
	}

	/*
	 * 标准注册入口
	 */
	public function action_register ()
	{
		if (site::type() == 'merchant')
			$this->template->set_filename('smarty:passport/register');

		if(site::type() == 'manager')
			$this->request->redirect('http://'.site::domain('merchant').'/register',302);

		// 注册成功后跳转的页面
		$ru = $this->request->query('ru');
		if (! empty($ru_get))
			$ru = Util::xssFilter($ru_get, FILTER_SANITIZE_STRING);
		else
		{
			$ru = $this->request->url(array(
					'controller' => 'passport', 
					'action'     => 'login_callback', 
				), 'http');
			$ru .= '?referer=' . rawurlencode($this->request->referrer());
		}


		$this->template->set("page_title", "注册");
		$this->template->set("return_url", $ru); 
		$this->template->set("include_jquery_validation", TRUE);
	}

    /**
     * 修改密码
     *
     */
    public function action_passwd ()
    {
        $this->template->set_filename("smarty:passport/passwd/reset");
        $post = $this->request->post();

        if (empty($post))
        {
        }
        else
        {
            $pwd0 = Arr::get($post, 'origpasswd', '');
            $pwd1 = Arr::get($post, 'newpasswd1', '');
            $pwd2 = Arr::get($post, 'newpasswd2', '');

            try 
            {
                if ($pwd1 != $pwd2)
                    throw new Exception_Invalid("新密码前后不一致");

                if (strlen($pwd1) > 18  || strlen($pwd1) < 6)
                    throw new Exception_Invalid("密码格式错误");

                $passport = new Passport;
                if (! $passport->reset_password(user::passport(), $pwd0, $pwd1))
                    throw new Exception_Invalid("密码错误");

                $this->template->set('alert_message', "密码修改成功!");
            }
            catch(Exception $e)
            {
                $this->template->set('alert_message', $e->getMessage());
            }
        }
    }

	/*
	 * 处理用户注册
	 */
	public function action_handle_register ()
	{
        $status  = 'VALID';
        $message = '';

        try {

            $post = $this->request->post();

            $passport = Arr::get($post, 'userid');
            $password = Arr::get($post, 'passwd');
            $realname = Arr::get($post, 'realname');
            $mobile   = Arr::get($post, 'mobile');
            $type     = Arr::get($post, 'type');
            $type     = $type == 'channel' ? 'default' : 'limit';
            $code     = strtolower(Arr::get($post, 'checkcode'));

		    $img = new securimage();
		    $codeServer  = strtolower($img->getCode());
            if ($codeServer != $code)
            {
			    throw new Exception("图片验证码错误, $codeServer,".print_r($post, TRUE));
            }


            account::create_account_raw($passport, $password, $realname, $mobile, $type, 0);
        }
        catch (Exception $e)
        {
            $status = 'EXISTS';
            $message= $e->getMessage();
        }

		$response = array('status' => $status, 'message' => $message);
        echo json_encode($response);
        exit;
	}

	/*
	 * 处理重新发送激活邮件
	 */
	public function action_send_mail()
	{
		$passport = $this->request->query('passport');
		$passwd   = $this->request->query('passwd');
		$nickname = $this->request->query('nickname');
		$ru       = $this->request->query('ru');
		$ru       = empty($ru)?$this->url_login_ru():$ru;

		if(empty($passport) || empty($passwd) || empty($nickname) || empty($ru))
			throw new SCException('参数错误!');

		$this->_passport->send_mail($passport, $passwd, $nickname, $ru);
		$this->template->set_filename('smarty:passport/activate_send_mail');
		$this->template->set('email_login',Util::getWebmailAddressFromEmail($passport));
		$this->template->set('passport',$passport);
		$this->template->set('passwd',$passwd);
		$this->template->set('nickname',$nickname);
		$this->template->set('ru',$ru);
	}


	/*
	 * 登录回调入口
	 *
	 */
	public function action_login_callback ()
	{
		$ru = $this->request->query('referer');	
		$status = $this->request->query('status');

		if ($status == 0)
		{
			if (user::current_user()->is_merchant() && site::type() != 'manager')
			{
				$url = 'http://' . site::domain('merchant');
				try {

					$merchant = user::factory(user::passport(), 'merchant');
					$merchant->set_last_login();
					$shop_id  = $merchant->shop_id();
				}
				catch (Exception $e) { }
			}
			else
			{
				user::current_user()->set_last_login();
				$url = empty($ru) ? '/'  : $ru;
			}

			$this->request->redirect($url);
		}
		else
		{
			$this->request->redirect('/passport/login');
		}
	}

	public function action_logout ()
	{
        $p = new Passport;
        $p->logout();
        $this->request->redirect('/admin/');
	}


	public function action_ajax($type)
	{
		$response = array('status' => 0);
		switch ($type)
		{
		case 'auth' :
			$response = $this->ajax_auth();
			break;

		case 'checkcode' :
			$response = $this->ajax_checkcode();
			break;

		case 'email' :
			$response = $this->ajax_email();
			break;

		case 'nickname' :
			$response = $this->ajax_nickname();
			break;

		default :
			break;
		}

		$str = json_encode($response);
		echo $str;exit;
		return;
	}

	/*
	 * 验证GET来的用户登录信息(passport)是否有效
	 *
	 * 返回:
	 *	VALID : 正确
	 *	INVALID: 错误
	 *	INACTIVE: 未激活
	 */
	private function ajax_auth () 
	{
        $p = new Passport;
		$userid   = $this->request->query('userid');
		$passwd   = $this->request->query('passwd');
		$mobile   = $this->request->query('mobile'); 
		
		if (!empty($mobile))
		{
            /*
			$response = $ihomeApi->wapGetUserId($mobile);
			if (isset($response['status']) && $response['status'] == 0)
				$userid = $response['userid'];
            */
		}
		
		$status = 'INVALID';
		if (!empty($userid))
		{
                if ($p->login($userid, $passwd))
				{
					$status = "VALID";
				}
                else
                {
                    $status = "INVALID";
                }

                /*
				else if ($response['status'] == 4) 
				{
					$status = 'INACTIVE';
				} 
				else 
				{ 
					$status = "INVALID";
				} // $stats != 4

				if($status == 'VALID' && Site::type() == 'merchant')
				{
					$merchant = User::factory($userid, 'merchant');
					if(!empty($merchant))
					{
						$shop_id = $merchant->shop_id();
						if(!Shop::passed_audit($shop_id))
							$status = 'CLOSED';
					}
				}
                 */
		} // !empty($userid)

		$response = array('userid' => $userid, 'status' => $status, 'passwd' => md5($passwd));
		return $response;
	}


	/*
	 * 验证码校验
	 *
	 */
	private function ajax_checkcode ()
	{
		$img = new Securimage();
		$codeServer  = strtolower($img->getCode());
		$codeEntered = strtolower($this->request->query('code'));
		
		$response = array('status' => '1',);
		if (!empty($codeServer) && !empty($codeEntered) 
				&& ($codeServer == $codeEntered))
		{
			$response['status'] = 0;
		}

		return $response;
	}

	/*
	 * 设置用户关注搜狐微博上搜狐爱家团账户
	 *
	 * 返回: status 
	 *
	 */
	private function ajax_sblog_tuan () 
	{
		$userid   = $this->request->query('userid');
		$passwd   = $this->request->query('passwd');

		$sblog    = new MicroBlogAction();
		$status   = $sblog->followTuan ($userid, $passwd);

		$response = array('userid' => $userid, 'status' => $status);
		return $response;
	}


	// 检查Email是否已经被占用
	private function ajax_email ()
	{
		$email = $this->request->query('email');
        if (passport::has_email ($email))
		    $response = array('status' => 4);
        else
            $response = array('status' => 0);

        /*
		// SohuPassport 中检查是否已经注册
		if (! empty($email))  
		{
			$email = iconv('utf8', 'gbk', $email);
			$sohuPassportApi = new ComSohuPassportApi();
			$response = $sohuPassportApi->userExist(strtolower($email));
		}

		if (!empty($response) AND $response['status'] != 0)
		{
			if (user::has_user($email))
				$response['status'] = 4;
		}
         */

		return $response;
	}

	private function ajax_nickname()
	{
		$nick = $this->request->query('nickname');
		$response = array('status' => 1);

		if (empty($nick))
			$response = array('status' => 1, 'message' => '昵称无效');

		try {
			passport::valid_nickname($nick);
			$response = array('status' => 0);
		}
		catch (SCException $e)
		{
			$response = array('status' => 1, 'message' => $e->getMessage());
		}
		catch (Exception $e)
		{
			$response = array('status' => 0, 'message' => '昵称无法使用');	
		}

		return $response;
	}

	/*
	 * 用户激活帐户入口
	 */
	public function action_activate ()
	{
		if (user::is_activated())
		{
			Request::$current->redirect('/admin');
		}

		// XSS protection
		///////////////////////////////////////////////////////////////////////
		if (isset($_GET['email']))
			$_GET['email'] = Util::xssFilter($_GET['email'], FILTER_SANITIZE_EMAIL);

		if (isset($_GET['ru']))
			$_GET['ru'] = Util::xssFilter($_GET['ru'], FILTER_SANITIZE_STRING);

		$return_url = isset($_GET['ru']) ? trim(Util::xssFilter($_GET['ru'], FILTER_SANITIZE_STRING)) : '';
		if (empty($return_url))
			$return_url = 'http://' . site::domain() . '/';
		
		$email = isset($_GET['email']) ? strtolower(trim($_GET['email'])) : NULL;
		$auth_str = isset($_GET['auth']) ? trim(Util::xssFilter($_GET['auth'], FILTER_SANITIZE_STRING)) : '';

		$passport   = $email;
		$md5_passwd = $this->request->query('passwd');
		$passwd     = $md5_passwd;

		if (! Passport::check_auth ($passport, $md5_passwd, $auth_str))
		{
			$this->template->set_filename('smarty:passport/activate_fail');
		}
		else
		{
			if ($this->_passport->activate ($passport))
			{
				$forward   = passport::url_auto_login ($passport, $return_url, $passwd, 'MD5');
				$this->template->set_filename('smarty:passport/activate_succ');
				$this->template->set('page_title', '账户激活成功');
				$this->template->set('forward_to', $forward);
			}
			else
			{
				$this->handle_activate_failure ($passport);
			}
		}
	}

	private function url_login_ru ()
	{
		$url = $this->request->url(array(
					'controller' => 'passport', 
					'action'     => 'login_callback', 
				), 'http');
		$url .= '?referer=' . rawurlencode($this->request->referrer());
		
		return $url;
	}

	/*
	 * 处理激活帐户失败 : 内部激活失败，安全验证通过
	 */
	private function handle_activate_failure ($passport)
	{
		$this->request->redirect('/admin');
	}
}
